package main

import (
	"fmt"
	"math/rand"
	"time"
)

func createServer() chan int{
	out := make(chan int)
	go func(){
		i:=0
		for{
			time.Sleep(time.Duration(rand.Intn(1500))* time.Millisecond)
			out <- i
			i++
		}
	}()
	return out
}
func createClient(id int) chan <- int{
	out := make(chan int)
	go func(){
		for o := range out{
			time.Sleep(time.Second)
			fmt.Printf("client %d receive %d\n",id, o)
		}
	}()
	return out
}
//模拟两个生产者生产消息，由一个消费者消费
//通过通讯来共享数据（CSP）,不需要锁和同步
func main() {
	//10s退出
	timeEnd := time.After(10 * time.Second)
	timeOut := time.After(800 * time.Millisecond)
	timeIntervel := time.Tick(time.Second)
	s1,s2 := createServer(),createServer()
	client := createClient(0)

	n:=0
	//解决客户端接收太慢，导致服务端发送的多个数据，冲掉原来的记录
	var queue []int
	for{
		//解决初始时服务端还没发送数据，客户端就开始接收的问题
		var activeClient chan <- int
		var activeQueueValue int
		if len(queue) >0 {
			activeClient = client
			activeQueueValue = queue[0]
		}
		select {
			case n =<-s1:
				//追加队列
				queue = append(queue, n)
			case n =<-s2:
				queue = append(queue, n)
			case activeClient <- activeQueueValue:
				//发送客户端后，重新更新队列
				queue = queue[1:]
			case <-timeOut:
				fmt.Println("time out")
			case <-timeIntervel:
				fmt.Printf("queue len %d\n", len(queue))
			case <-timeEnd:
				fmt.Println("Bye bye")
				return
		}
	}

}
